#include <iostream>
#include <string>
#include <fstream>
#include <chrono>
#include "viml/vm.h"
#include "viml/compiler.h"
#include "viml/parser.h"
#include "viml/ast_printer.h"

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "用法: " << argv[0] << " <script.vim>" << std::endl;
        return 1;
    }

    std::string filename = argv[1];

    try {
        // 读取源文件
        std::ifstream file(filename);
        if (!file.is_open()) {
            std::cerr << "错误: 无法打开文件 " << filename << std::endl;
            return 1;
        }

        std::string source((std::istreambuf_iterator<char>(file)),
                          std::istreambuf_iterator<char>());
        file.close();

        // 创建编译器和虚拟机
        viml::Compiler compiler;
        viml::VM vm;

        // 启用记忆化
        vm.set_memoization_enabled(true);
        vm.optimize_memoization_for_recursive_algorithms();
        
        // 关键：自动分析并添加纯函数到白名单
        viml::Parser parser(source);
        auto program = parser.parse();
        
        std::cout << "正在进行自动函数纯度分析..." << std::endl;
        for (auto& stmt : program->statements) {
            if (auto func_stmt = dynamic_cast<viml::FunctionStatement*>(stmt.get())) {
                std::cout << "分析函数: " << func_stmt->name << std::endl;
                auto result = vm.analyze_and_add_function(*func_stmt);
                if (result.is_pure) {
                    std::cout << "  ✓ " << func_stmt->name << " 已添加到记忆化白名单" << std::endl;
                } else {
                    std::cout << "  ✗ " << func_stmt->name << " 未添加到记忆化白名单: " << result.reason << std::endl;
                }
            }
        }
        
        // 编译源代码
        std::cout << "编译 " << filename << "..." << std::endl;
        auto bytecode = compiler.compile(source, filename);
        
        // 执行字节码
        std::cout << "执行中..." << std::endl;
        auto start_time = std::chrono::high_resolution_clock::now();
        auto result = vm.execute(bytecode);
        auto end_time = std::chrono::high_resolution_clock::now();
        
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
        
        std::cout << "执行完成" << std::endl;
        std::cout << "执行时间: " << duration.count() / 1000.0 << "ms" << std::endl;
        
        // 显示记忆化统计
        auto stats = vm.get_memoization_statistics();
        std::cout << "记忆化统计:" << std::endl;
        std::cout << "  缓存命中: " << stats.hits << " 次" << std::endl;
        std::cout << "  缓存未命中: " << stats.misses << " 次" << std::endl;
        std::cout << "  命中率: " << stats.hit_rate << "%" << std::endl;
        
        return 0;

    } catch (const std::exception& e) {
        std::cerr << "错误: " << e.what() << std::endl;
        return 1;
    }
}